#include "taskworker.h"
#include <QThread>

TaskWorker::TaskWorker() {}

void TaskWorker::onSend(const QByteArray &arr) {
  qDebug() << "onSend threadId=" << QThread::currentThreadId();
  m_tcpClient->write(arr);
}

void TaskWorker::onConnect(const QString &ip, quint16 port) {

  m_tcpClient = new QTcpSocket();
  // 连接到服务端 信号槽 ,lamba表达式的写法
  connect(
      m_tcpClient, &QTcpSocket::connected, this,
      [this] { emit showMessage("连接服务器成功!", true); },
      Qt::DirectConnection);

  // 断开连接信号
  connect(
      m_tcpClient, &QTcpSocket::disconnected, this,
      [this] { emit showMessage("连接被断开!", false); }, Qt::DirectConnection);

  // 有数据可读的信号,Qt::DirectConnection,确保在子线程中执行。
  connect(m_tcpClient, &QTcpSocket::readyRead, this, &TaskWorker::onReadyRead,
          Qt::DirectConnection);

  // 连接到TCP服务端
  qDebug() << "connect 连接 " << QThread::currentThreadId();

  m_tcpClient->connectToHost(ip, port);
}

void TaskWorker::onReadyRead() {
  qDebug() << "接收数据 " << QThread::currentThreadId();
  QByteArray data = m_tcpClient->readAll();
  QString str = QString("收到数据: %1").arg(QString(data));
  emit showMessage(str, true);
}

void TaskWorker::onClose() {
  qDebug() << "onClose " << QThread::currentThreadId();

  // 关闭与服务端的连接
  m_tcpClient->disconnectFromHost();
  m_tcpClient->deleteLater();
}
